package com.digital.welcome.websocket.model;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.function.Consumer;

import org.apache.kafka.common.protocol.types.Field.Str;

import com.alibaba.fastjson.JSON;
import com.digital.welcome.websocket.mywebsocket.model.WebSocketMessage;
import com.digital.welcome.websocket.mywebsocket.model.WebSocketMessageEvent;
import com.digital.welcome.websocket.mywebsocket.model.WebSocketMessageType;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.hutool.json.JSONObject;

public class Message {

    public static String SEND_USER_ID = "SendUserID";
    public static String RECEIVE_ID = "ReceiveID";

    public Long id;
    public Long sendUserId;
    public Long receiveUserId;
    @JsonFormat(pattern = "yyyy-MM-dd\'T\'HH:mm:ss")
    public Date time;
    public String contentType;
    public Object content;

    public Message(long id, long sendUserID, long receiveID, Date time, String MessageContentType, Object content) {
        this.id = id;
        this.sendUserId = sendUserID;
        this.receiveUserId = receiveID;
        this.time = time;
        this.contentType = MessageContentType;
        this.content = content;
    }

    public static class MessageContentType {
        public static String Text = "text/plain";
        public static String Gif = "image/gif";
        public static String Jpg = "image/jpeg";
        public static String Png = "image/png";

    }

    public static ArrayList<WebSocketMessage> ToWebSocketMessageList(ArrayList<Message> messages,
            WebSocketMessageEvent wsmEvent) {
        ArrayList<WebSocketMessage> msgList = new ArrayList<WebSocketMessage>();
        messages.forEach(new Consumer<Message>() {
            @Override
            public void accept(Message message) {
                try {
                    if (MessageContentType.Text.equals(message.contentType)) {
                        msgList.add(new WebSocketMessage(
                                wsmEvent,
                                WebSocketMessageType.Text,
                                new ObjectMapper().writeValueAsString(message)));
                        
                    } else {
                        Object bytes = message.content;
                        message.content = null;
                        msgList.add(new WebSocketMessage(
                                wsmEvent,
                                WebSocketMessageType.Text,
                                new ObjectMapper().writeValueAsString(message)));
                        msgList.add(new WebSocketMessage(
                                wsmEvent,
                                WebSocketMessageType.Binary,
                                bytes));

                        message.content = bytes;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        });

        return msgList;
    }

        /// <summary>
		/// 将套接字消息转为私聊消息
		/// </summary>
		/// <param name="wsMessages"></param>
		/// <param name="offset">从第offset条套接字消息开始截取, 默认为0</param>
		/// <param name="length">选择截取length条套接字消息作为消息, 默认为-1, 即从offset开始的所有消息</param>
		/// <returns></returns>
        public static int TO_MESSAGES_PROP_OFFSET = 0;
        public static int TO_MESSAGES_PROP_LENGTH = -1;
		public static ArrayList<Message> ToMessages(ArrayList<WebSocketMessage> wsMessages, int offset, int length) throws ParseException
		{
			ArrayList<Message> result = new ArrayList();
			int _offset = offset;
			while (_offset < wsMessages.size() && (_offset - offset < length || length == -1))
			{
                // Message message = JSON.parseObject((String)wsMessages.get(_offset).getMessage(), Message.class);
                // message.contentType 被解析为null, 所以手动写死
                // 自行解析
                JSONObject messageJson = new JSONObject((String)wsMessages.get(_offset).getMessage());
                Message message = new Message(
                    (Integer)messageJson.get("id"),
                    (Integer)messageJson.get("sendUserId"),
                    (Integer)messageJson.get("receiveUserId"),
                    new SimpleDateFormat("yyyy-MM-dd\'T\'HH:mm:ss").parse((String)messageJson.get("time")),
                    (String)messageJson.get("contentType"), 
                    messageJson.get("content"));
                    
                //
				if (!MessageContentType.Text.equals(message.contentType))
				{
					byte[] bytesContent = (byte[])wsMessages.get(_offset + 1).getMessage();
					message.content = bytesContent;
					result.add(message);
					_offset += 2;
				}
				else
				{
					result.add(message);
					_offset++;
				}

			}

			return result;

		}
}
